package org.springblade.modules.admin.service.parts.impl.strategy;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;
import org.springblade.common.constant.MaintenanceSmsConstant;
import org.springblade.common.constant.TemplateMsgConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.BusinessApprove;
import org.springblade.modules.admin.entity.MaintainMalfunctionLog;
import org.springblade.modules.admin.entity.MaintainPlanContent;
import org.springblade.modules.admin.enums.ApproveStatusEnum;
import org.springblade.modules.admin.enums.ApproveTypeEnum;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.service.approve.strategy.ApproveBusinessFlow;
import org.springblade.modules.admin.service.approve.strategy.ApproveBusinessStrategy;
import org.springblade.modules.admin.service.parts.AbstractOrderStateStrategy;
import org.springblade.modules.admin.utils.AsyncUtils;
import org.springblade.modules.admin.vo.BusinessApproveVO;
import org.springblade.modules.admin.vo.parts.PartsExecuteVO;
import org.springblade.modules.resource.utils.SmsUtil;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.vo.SimpleUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 已关闭策略实现 -> 对应状态8
 * @Author ysq
 * @Date 2024/05/23
 **/
@Slf4j
@Service("closeOrderStrategy")
public class CloseOrderStrategyImpl extends AbstractOrderStateStrategy {

	@Autowired
	private AsyncUtils asyncUtils;

	@Override
	public Object handle(PartsExecuteVO executeParams) {
		BusinessApprove businessApprove = businessApproveService.getByWorkOrderId(executeParams.getPlanId());
		if (businessApprove == null) {
			log.error("审批流程不存在!, 工单id：[{}]", executeParams.getPlanId());
			return R.status(false);
		}
		// 更新审批 -> 审批不通过
		BusinessApproveVO businessApproveVO = new BusinessApproveVO();
		businessApproveVO.setId(businessApprove.getId());
		businessApproveVO.setApproveStatus(ApproveStatusEnum.REJECT.getId());
		businessApproveVO.setRemark(executeParams.getRemark());
		ApproveBusinessFlow flowStrategy = ApproveBusinessStrategy.get(ApproveTypeEnum.ACCESSORY_APPLY.getId());
		boolean flowRes = flowStrategy.approve(businessApproveVO);
		if (!flowRes) {
			log.error("状态流转失败, 工单id：[{}]", executeParams.getPlanId());
			return R.status(false);
		}
		executeParams.setTargetStatus(TaskStatusEnum.PARTS_CLOSE.getStatus());
		return super.handle(executeParams);
	}

	@Override
	public void after(PartsExecuteVO executeParams) {
		List<MaintainMalfunctionLog> maintainMalfunctionLogList = maintainMalfunctionLogService.list(Wrappers.<MaintainMalfunctionLog>lambdaQuery().eq(MaintainMalfunctionLog::getPlanId, executeParams.getPlanId()).orderByDesc(MaintainMalfunctionLog::getId));
		MaintainMalfunctionLog maintainMalfunctionLog = null;
		if (Func.isNotEmpty(maintainMalfunctionLogList)) {
			// 更新任务追踪日志
			maintainMalfunctionLog = maintainMalfunctionLogList.get(0);
			maintainMalfunctionLog.setExt(JSONObject.toJSONString(MapUtil.ofEntries(MapUtil.entry("approveDesc", ApproveStatusEnum.REJECT.getName()), MapUtil.entry("remark", executeParams.getRemark()))));
			maintainMalfunctionLogService.updateById(maintainMalfunctionLog);
		}

		// 插入任务追踪日志
		maintainMalfunctionLogService.insertWorkLog(executeParams.getPlanId(),
			TaskStatusEnum.PARTS_CLOSE.getName(),
			TaskStatusEnum.valueOf(executeParams.getEvent()).getStatus(),
			null,
			AuthUtil.getUserId(),
			null);

		/**
		 * 2024-06-21 新增发送消息
		 */
		Long currentPlanId = executeParams.getPlanId();
		if(!Func.isNull(currentPlanId)){
			MaintainPlanContent maintainPlanContent = maintainPlanContentService.getById(currentPlanId);
			Long createUserId = maintainPlanContent.getCreateUser();
			User createUser = userService.getById(createUserId);
			log.info("===========配件申请退回-发送手机短信,接收人:[{}], 手机号码:[{}]===========", createUser.getRealName(), createUser.getPhone());
			Map<String, String> smsParam = new HashMap<>(4);
			smsParam.put("auditType", "审批不通过");
			SmsUtil.sendMessage(MaintenanceSmsConstant.AUDIT_FAILED, BladeConstant.ADMIN_TENANT_ID, smsParam, createUser.getPhone());
			Long closeUserId = AuthUtil.getUserId();
			User closeUser = userService.getById(closeUserId);
			// 审批退回，发送公众号消息提醒
			SimpleUserVO applyUserInfo = userService.getSimpleUserInfo(maintainPlanContent.getCreateUser());
			if (Func.isNotEmpty(applyUserInfo.getOpenid())) {
				// 跳转链接
				String skipUrl = String.format("pages/approve/partApprovalDetail?id=%s&type=3", executeParams.getPlanId());
				Map<String, String> templateDataMap = new HashMap<>(8);
				templateDataMap.put("first", "审批结果通知");
				templateDataMap.put("keyword1", "审批不通过");
				templateDataMap.put("keyword2", closeUser.getRealName());
				templateDataMap.put("keyword3", DateUtil.now());
				templateDataMap.put("remark", "请前往梯无忧维保小程序【我的申请】重新提交处理");
				templateDataMap.put("params", skipUrl);
				asyncUtils.sendWeiXinTemplate(applyUserInfo.getOpenid(), TemplateMsgConstant.T_APPROVE_RESULT_ID, templateDataMap);
				log.info("===========发送审批结果模板消息,申请人:[{}]===========", applyUserInfo.getUserName());
			}
		}
	}
}
